<template>
  <div class="kuaijiehuifu-content">
    <el-popover placement="top-start" width="400" trigger="click">
      <div class="set-reply">
        <span class="set-reply-title">{{$t('im.imChat.components.messageBox.quickReply.des1')}}</span
        ><span class="set-button" @click="setReply">{{$t('common.base.setting')}}</span>
      </div>
      <template v-if="replyList.length > 0">
        <!-- 回复列表-start -->
        <ul class="quickReply-list">
          <template v-if="isNotSearch">
            <li
              class="quickReply-list-item cursor"
              v-for="(v, i) in replyList"
              :key="v.id"
              @click="sendReply(v.content)"
            >
              <el-tooltip :disabled="v.content.length <= 40" :content="v.content" placement="top">
                <span class="text content-text">{{ v.content }}</span>
              </el-tooltip>
              <span class="send-btn" @click.stop="sendMsg(v.content,true)">发送</span>
            </li>
          </template>
          <template v-else>
            <li
              class="quickReply-list-item cursor"
              v-for="(v, i) in searchList"
              :key="v.id"
              @click="sendReply(v.content)"
            >
              <el-tooltip :disabled="v.content.length <= 40" :content="v.content" placement="top">
                <span class="text content-text" v-html="v.searchContent"></span>
              </el-tooltip>
              <span class="send-btn" @click.stop="sendMsg(v.content,true)">发送</span>
            </li>
            <div v-if="!searchList.length">{{ $t('common.base.tip.noResultForSearch') }}</div>
          </template>
        </ul>
        <!-- 回复列表-end -->
        <el-input v-model="keyword" :placeholder="$t('common.base.inputKeywordToSearch2')" clearable />
      </template>
      <div v-else class="default">
        <div class="default-img">
          <img :src="noDataImage" alt="" />
        </div>
        <div class="default-msg">{{$t('common.base.tip.noData')}}</div>
      </div>
      <label slot="reference">
        <el-tooltip class="item" effect="dark" :content="$t('im.imChat.components.messageBox.quickReply.des1')" placement="top">
          <i
            v-track="$track.formatParams('CHAT_QUICK_REPLY')"
            class="iconfont icon-icon-kuaijiehuifu icon-kuaijiehuifu"
            :style="{
              color: disabled ? '#bfbfbf' : '',
              cursor: disabled ? 'not-allowed' : 'pointer',
            }"
          ></i>
        </el-tooltip>
        
      </label>
      <!-- <i class="iconfont icon-icon-kuaijiehuifu icon-kuaijiehuifu" slot="reference" :style="{color: disabled ? '#bfbfbf': '',cursor: disabled ? 'not-allowed': 'pointer'}"></i> -->
    </el-popover>
    <!-- 设置快捷回复弹窗 -->
    <el-dialog
      :title="$t('im.imChat.components.messageBox.quickReply.title1')"
      :visible.sync="visible"
      width="50%"
      @close="close"
    >
      <!-- 内容主体区域 -->
      <template v-if="(editList.length+replyList.length)>0">
        <ul class="quickReply-list quickReply-list-edit" id="quickReply-list">
          <!-- 编辑列表 -->
          <li
            class="quickReply-list-item quickReply-list-item-edit"
            :class="{ ptb4: !v.isEdit }"
            v-for="(v, i) in editList"
            :key="v.id"
          >
            <el-tooltip v-if="v.isEdit" :content="v.content" placement="top">
              <span class="text content-text"
              >{{ v.content }}</span
              >
            </el-tooltip>
            <div class="text-box" v-if="!v.isEdit">
              <div class="text">
                <el-input
                  type="textarea"
                  autosize
                  class="textarea"
                  v-model="v.content"
                ></el-input>
              </div>
            </div>
            <span class="edit-btn">
              <el-button
                v-if="v.isEdit"
                class="send-btn"
                type="text"
                size="small"
                @click="v.isEdit = !v.isEdit"
              >{{$t('common.base.edit')}}</el-button
              >
              <el-button
                v-if="!v.isEdit"
                class="send-btn"
                type="text"
                size="small"
                @click="submitForm(v, i)"
              >{{$t('common.base.finish')}}</el-button
              >
              <el-button
                class="send-btn"
                type="text"
                size="small"
                @click="deleteEdit(i)"
              >{{$t('common.base.delete')}}</el-button
              >
            </span>
          </li>
          <!-- 回复列表 -->
          <li
            class="quickReply-list-item"
            :class="{ ptb4: !v.isEdit }"
            v-for="(v, i) in replyList"
            :key="v.id"
          >
            <el-tooltip :disabled="v.content.length <= 95" v-if="v.isEdit" :content="v.content" placement="top">
              <span class="text content-text"
              >{{ v.content }}</span
              >
            </el-tooltip>
            <div class="text-box" v-if="!v.isEdit">
              <div class="text">
                <el-input
                  type="textarea"
                  autosize
                  class="textarea"
                  v-model="v.content"
                ></el-input>
              </div>
            </div>
            <span class="edit-btn">
              <el-button
                v-if="v.isEdit"
                class="send-btn"
                type="text"
                size="small"
                @click="v.isEdit = !v.isEdit"
              >{{$t('common.base.edit')}}</el-button
              >
              <el-button
                v-if="!v.isEdit"
                class="send-btn"
                type="text"
                size="small"
                @click="submitForm(v)"
              >{{$t('common.base.finish')}}</el-button
              >
              <el-button
                class="send-btn"
                type="text"
                size="small"
                @click="deleteQuickReply(v.id)"
              >{{$t('common.base.delete')}}</el-button
              >
            </span>
          </li>
        </ul>
      </template>
      <div v-else class="default" style="height:300px">
        <div class="default-img">
          <img :src="noDataImage" alt="" />
        </div>
        <div class="default-msg">{{$t('common.base.tip.noData')}}</div>
      </div>
      <span class="set-button" @click="addReply">{{$t('im.imChat.components.messageBox.quickReply.des2')}}</span>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="visible = false"
        >{{$t('common.base.confirm')}}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as IMApi from '@src/api/ImApi.js';
import FileMixin from './FileMixin.js';
import EventBus from '@src/util/eventBus';
import { customerServiceSendNewMessage } from '@src/modules/im/imChat/components/messageBox/send.js';
import { isEmpty } from '@src/util/type'
import { getOssUrl } from '@src/util/assets'
import { cloneDeep } from 'lodash';
import { filterXss } from '@src/util/window.ts'
const noDataImage = getOssUrl('/no_data.png')
export default {
  name: 'quick-reply',
  mixins: [FileMixin],
  props: {
    disabled: {
      type: Boolean,
    },
    CurrentConversationInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      noDataImage,
      replyList: [],
      visible: false,
      editList: [],
      keyword: '',
    };
  },
  computed: {
    isNotSearch() {
      return isEmpty(this.keyword);
    },
    searchList() {
      let newArr = []
       this.replyList.forEach(v => {
        if(v.content.includes(this.keyword)){
          let v_ = cloneDeep(v)
          let con_ = filterXss(v_.content)
          v_['searchContent'] = con_.replaceAll(this.keyword, `<span class="color-primary">${this.keyword}</span>`)
          newArr.push(v_)
        }
      });
      return newArr
    },
  },
  created() {
    this.getQuickReplyList();
  },
  methods: {
    sendReply(content) {
      if (this.CurrentConversationInfo.conversationStatus == 3) {
        return this.$platform.alert(this.$t('im.imChat.components.messageBox.quickReply.tips1'));
      }
      if (this.CurrentConversationInfo.timeOut == 1) {
        return this.$platform.alert(this.$t('im.imChat.components.messageBox.quickReply.tips2'));
      }
      this.sendSubmitForm(content);
    },
    /**
     * deleteQuickReply 删除快捷回复
     * @param {number|string} id id标识
     */
    deleteQuickReply(id) {
      this.$confirm(this.$t('im.imChat.components.messageBox.quickReply.tips3'), this.$t('im.imChat.components.messageBox.quickReply.tips4'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(async () => {
        const params = {
          id,
        };
        try {
          await IMApi.deleteQuickReply(params);
          await this.getQuickReplyList();
        } catch (err) {
          this.$platform.alert(this.$t('common.base.tip.deleteSuccess'));
          console.error('deleteQuickReply', err);
        }
      });
    },
    sendSubmitForm(message) {
      EventBus.$emit('sendReply', message);
      this.closePopover()
    },
    async addReply(item) {
      this.editList.push({ content: '', isEdit: false });
      document.getElementById('quickReply-list').scrollTop = 0;
    },
    async submitForm(item, editIdx) {
      if (!item.content) {
        this.$message.error(this.$t('common.placeholder.inputContent'));
        return;
      }
      const params = {
        id: item.id ? item.id : '',
        content: item.content,
      };
      console.log('item', item);
      try {
          if(item.id) {
            await IMApi.updateQuickReply(params)
          } else {
            const { success, message } = await IMApi.addQuickReply(params);
            if(!success) this.$message.warning(message)
          }
        if (!(typeof editIdx === 'undefined')) {
          this.deleteEdit(editIdx);
        }
      } finally {
        item.isEdit = true;
        this.getQuickReplyList();
      }
    },
    setReply() {
      this.visible = true;
    },
    async getQuickReplyList() {
      try {
        const { code, message, data } = await IMApi.getQuickReplyList();
        if (code == 0) {
          data.forEach(v => {
            v.isEdit = true;
          });
          this.replyList = data;
        } else {
          this.$message.error(message)
        }
      } catch (err) {
        console.error('getQuickReplyList', err);
      }
    },
    deleteEdit(i) {
      this.editList.splice(i, 1);
    },
    close() {
      this.editList = [];
      this.getQuickReplyList();
    },
    async sendMsg(val,isClose = false){
      const params = {
        conversationId: this.CurrentConversationInfo.id,
        messageType: 'txt',
        messageContent: {
          msg: val
        },
      };
      const messageInfo = await customerServiceSendNewMessage(params);
      EventBus.$emit('addMessageByKF', messageInfo);
      if(isClose) this.closePopover()
    },
    closePopover(){
      document.body.click()
    }
  },
};
</script>
<style lang="scss" scoped>
.kuaijiehuifu-content {
  display: inline-block;
}
.icon-kuaijiehuifu {
  color: #8c8c8c;
  cursor: pointer;
}
.icon-kuaijiehuifu:hover {
  color: $color-primary-light-6;
}
.set-reply {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  .set-reply-title {
    color: #262626;
    font-weight: bold;
  }
}
.set-button {
  color: $color-primary-light-6;
  cursor: pointer;
}
.quickReply-list {
  padding: 0;
  width: 100%;
  flex: 1;
  overflow-y: auto;
  height: 200px;
}
.quickReply-list-edit{
  height: 300px;
  max-height: 300px;
}
.quickReply-list-item {
  display: flex;
  justify-content: space-between;
  line-height: 20px;
  border-top: 1px solid #efefef;
  font-size: 13px;
  padding: 6px 6px 8px 0;
  align-items: center;
  &:hover{
    .send-btn{
      opacity: 1;
    }
  }
  .send-btn{
    margin-left: 15px;
    opacity: 0;
    font-size: 12px;
    color: $color-primary-light-6;
    cursor: pointer;
  }
  .quickReply-list-item-edit {
  }
}
.cursor {
  cursor: pointer;
}
.text-box {
  width: 80%;
  .text {
    display: flex;
    width: 100%;
    .text-num{
      flex-shrink: 0;
    }
  }
}

.textarea {
  min-height: 32px;
  overflow-y: visible;
  // border: 1px solid #ccc;
  border-radius: 2px;
  // padding-left: 8px;
}
.content-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  -webkit-box-orient: vertical;
}
.hide {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  filter: alpha(opacity=0);
  opacity: 0;
  cursor: inherit;
  display: none;
}
.el-icon-paperclip {
  font-size: 14px;
  margin: 10px 0;
}
.ptb4 {
  padding: 4px 0;
}
.edit-btn {
  margin: 0 8px 0 14px;
  // flex: 0 0 80px;
  button {
    padding: 0;
  }
}
.default {
    background: #fff;
    position: relative;
    text-align: center;
    .default-img {
      img {
        width: 160px;
        height: 160px;
      }
    }
    .default-msg {
      text-align: center;
      margin-top: 8px;
      color: $text-color-regular;
    }
  }
</style>
